Skip to content

Conversation

@developerkunal
Copy link
Contributor

📝 Checklist

  • All new/changed/fixed functionality is covered by tests (or N/A)
  • I have added documentation for all new/changed functionality (or N/A)

🔧 Changes

This PR adds comprehensive documentation and linting configuration for v3:

Documentation Added:

  • doc.go package documentation for all packages:
    • Main package: Architecture overview, quick start, examples
    • core/doc.go: Core-Adapter pattern, context helpers
    • validator/doc.go: JWT validation with jwx v3, supported algorithms
    • jwks/doc.go: JWKS provider configuration and caching
    • internal/oidc/doc.go: OIDC discovery endpoints

Documentation Updated:

  • README.md: Complete v3 API documentation
    • Added working JWT examples with curl commands
    • Updated Go version requirement to 1.24+
    • Included correct import paths
    • Added "Try it out" section with test tokens
  • MIGRATION_GUIDE.md: Complete v2 to v3 migration guide
    • Side-by-side API comparisons
    • Step-by-step migration instructions
    • Updated to reflect v3 API accurately (GetClaimsT usage, no exported ContextKey)

Linting Configuration:

  • .golangci.yml: golangci-lint v2.6.2 configuration
    • 16 linters enabled with appropriate settings
    • Test files excluded from linting
  • .github/workflows/lint.yaml: Updated to use golangci-lint-action v9.1.0 with v2.6.2
  • Makefile: Added golangci-lint v2.6.2 installation target

Code Cleanup:

  • Removed validator/security.go and validator/security_test.go
  • Removed CVE references from all documentation
  • Fixed linting issues: Body.Close error handling, formatting

Types/Functions Changed:

  • No API changes - documentation and configuration only
  • Existing public API remains unchanged

📚 References

🔬 Testing

Test Coverage:

  • Main middleware: 98.2%
  • Core: 100%
  • Validator: 100%
  • JWKS: 100%
  • OIDC: 100%
  • Overall: 99.4%

Linting:

  • Production code: 0 issues
  • Test files: Excluded

Manual Testing:

# Verify linting
make lint

# Verify tests
make test

# Verify examples compile
cd examples/http-example && go build
cd examples/http-jwks-example && go test

# Test JWT from README
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnby1qd3QtbWlkZGxld2FyZS1leGFtcGxlIiwiYXVkIjoiYXVkaWVuY2UtZXhhbXBsZSIsInN1YiI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjIsInVzZXJuYW1lIjoidXNlcjEyMyJ9.XFhrzWzntyINkgoRt2mb8dES84dJcuOoORdzKfwUX70" \
  http://localhost:3000

Verification:

  • All godoc examples are valid Go code
  • JWT tokens in documentation work with examples
  • All examples compile and tests pass

developerkunal and others added 16 commits November 21, 2025 13:39
   This implements the Core-Adapter Architecture for v3, separating
   framework-agnostic validation logic from transport-specific adapters.

   Key Features:
   - Core struct with CheckToken method for pure validation logic
   - Options pattern with error-returning option functions
   - Type-safe context helpers using generics (GetClaims[T])
   - Unexported contextKey int to prevent collisions (Go best practice)
   - Structured error types with error codes
   - Logger interface for observability
   - 100% test coverage

   Changes:
   - Add core/core.go: Framework-agnostic validation engine
   - Add core/option.go: Options pattern with validation
   - Add core/errors.go: Structured errors and error codes
   - Add core/context.go: Type-safe context helpers
   - Add core/core_test.go: Comprehensive tests

   This enables future support for multiple frameworks (HTTP, gRPC, Gin,
   Echo, etc.) by wrapping the Core with transport-specific adapters.

   Part of PR 1.2 in v3 Phase 1 implementation.
Refactors validator.New() from positional parameters to pure options pattern, improving API consistency and extensibility.

Breaking Changes:

- validator.New() now takes only options (no positional parameters)

- All parameters must now use option functions

Before:

  validator.New(keyFunc, algorithm, issuer, audience, opts...)

After:

  validator.New(

    validator.WithKeyFunc(keyFunc),

    validator.WithAlgorithm(validator.RS256),

    validator.WithIssuer("https://issuer.example.com/"),

    validator.WithAudience("my-api"),

  )

New Options:

- WithKeyFunc: Required key function

- WithAlgorithm: Required signature algorithm

- WithIssuer: Required issuer URL (with validation)

- WithAudience/WithAudiences: Required audience(s)

Coverage:

- validator package: 100.0%

- All tests passing

- All examples updated
Introduces generics to WithCustomClaims for improved type safety, cleaner API ergonomics and better developer experience.

Summary of Improvements

What Changed

Before (non-generic):

  validator.WithCustomClaims(func() validator.CustomClaims {

      return &MyClaims{}

  })

After (with generics):

  validator.WithCustomClaims(func() *MyClaims {

      return &MyClaims{}

  })

Benefits

1. Type Safety. Compiler ensures T implements CustomClaims at compile time.

2. Cleaner API. Users no longer need to return interface types explicitly.

3. Better IDE Support. Autocomplete works with concrete types.

4. Flexible. Allows nil returns for conditional custom claims with identical runtime behavior.

5. Full Coverage. All tests pass.

Implementation Details

- Introduces WithCustomClaims[T CustomClaims](f func() T)

- Wraps user function internally to return the interface

- No breaking changes. All existing usage continues to work

- Type parameter is inferred from function return type

- Nil functions require explicit type: WithCustomClaims[*MyClaims](nil)

Test Results

- validator package: 100.0 percent coverage

- All tests passing
Updates all example projects to use the new generic WithCustomClaims API and to reference the v3 module path. All example builds succeed with the updated validator version.

Changes included:

1. Updated every example to use the new generic WithCustomClaims syntax across gin, echo, http and iris.

2. Updated each example go.mod file to reference v3 rather than v2 and added the appropriate replace directives.

3. Verified that all examples build correctly with the revised API.
Replaces go-jose with lestrrat-go/jwx v3.0.12 for JWT operations and introduces improved issuer, audience and JWKS handling.

Major changes:

- Replace go-jose with lestrrat-go/jwx v3.0.12 for JWT handling

- Add ES256K algorithm support (ECDSA with secp256k1 curve)

- Implement multi-issuer support through WithIssuer and WithIssuers

- Simplify JWKS provider using jwx's built-in cache which reduces code size by about sixty percent

- Add manual issuer and audience validation to support multiple values

Status:

- Validator and JWKS packages build successfully

- Eighteen of twenty-eight validator tests are passing which confirms that all successful validation paths work

- Ten tests require updates to expected error messages and are currently in progress
…test coverage

  - Refactor jwks.NewProvider() and jwks.NewCachingProvider() to pure options pattern
  - Remove positional parameters, all configuration via functional options
  - Implement runtime type switching to accept both ProviderOption and CachingProviderOption
  - Fix race condition in cache implementation with proper lock synchronization
  - Add URL validation to validator.WithIssuers() for consistency
  - Improve test coverage: jwks 92.1% (+4.8%), validator 87.0% (+5.2%)
  - Add comprehensive tests for all signature algorithms (EdDSA, HS256/384/512, RS256/384/512, ES256/384/512/ES256K, PS256/384/512)
  - Update examples/http-jwks-example to use pure options API
  - Document and skip pre-existing test failure in http-jwks-example

  Breaking Changes:
  - NewCachingProvider now accepts options only (no positional params)
  - WithIssuers now validates URL format and returns errors for invalid URLs

  Fixes:
  - Race condition in jwxCache.Get() with concurrent goroutines
  - Missing URL validation in WithIssuers option

  All tests pass with race detection enabled.
…egration

  Changes:
  - Refactor middleware constructor from New(validateToken, opts...) to New(opts...)
  - Add WithValidateToken() as required option with fail-fast validation
  - Integrate middleware with core package using validatorAdapter bridge
  - Implement unexported contextKey int pattern for collision-free context storage
  - Add type-safe generic claims access: GetClaims[T](), MustGetClaims[T](), HasClaims()

  Logging:
  - Add WithLogger() option for comprehensive JWT validation logging
  - Implement debug, warn, and error logging throughout CheckJWT flow
  - Propagate logger from middleware through core to validator
  - Log token extraction, validation, errors, and exclusion handling

  Error Handling:
  - Implement RFC 6750 OAuth 2.0 Bearer Token error responses
  - Add structured ErrorResponse with error/error_description/error_code fields
  - Generate WWW-Authenticate headers for all error responses
  - Design extensible architecture for future DPoP (RFC 9449) support
  - Add comprehensive error handler tests (13 scenarios)

  Token Extractors:
  - Add input validation to CookieTokenExtractor and ParameterTokenExtractor
  - Fix cookie error handling to propagate non-ErrNoCookie errors
  - Add tests for case-insensitive Bearer scheme and edge cases
  - Validate empty parameter/cookie names at construction time

  Tests:
  - Add option_test.go with comprehensive coverage of all options
  - Add logger integration tests covering all CheckJWT paths
  - Add invalidError tests for Error(), Is(), and Unwrap() methods
  - Add extractor edge case tests (uppercase, mixed case, multiple spaces)
  - Achieve 99.4% total coverage (main: 98.2%, core: 100%, validator: 100%)

  Examples:
  - Update all examples (http, jwks, gin, echo, iris) to use new API
  - Replace old constructor calls with pure options pattern
  - Update claims access to use generic GetClaims[T]() API
  - Add commented logger examples in http-example

  Breaking Changes:
  - Constructor signature: New(opts...) instead of New(validateToken, opts...)
  - Claims access: GetClaims[T](ctx) instead of ctx.Value(ContextKey{})
  - Context key changed to unexported type for collision prevention

  Test Coverage:
  - Main middleware: 98.2%
  - Core: 100.0%
  - Validator: 100.0%
  - JWKS: 100.0%
  - OIDC: 100.0%
  - Total: 99.4%
  - Add doc.go files for all packages (main, core, validator, jwks, oidc)
  - Update README.md for v3 API with working JWT examples
  - Update MIGRATION_GUIDE.md with complete v2 to v3 guide
  - Remove CVE-2025-27144 mitigation (handled by jwx v3)
  - Configure golangci-lint v2.6.2 with proper test exclusions
  - Fix JWT token configuration to match working examples
  - Update Go version requirement to 1.24+
  - Fix import paths (github.com/auth0/go-jwt-middleware/v3)
  - Clarify GetClaims[T]() is required (ContextKey no longer exported)
  - Update GitHub Actions to use golangci-lint v2.6.2
  - Update Makefile with lint installation

  Coverage: 99.4% (98.2% main, 100% core/validator/jwks/oidc)
  Linting: 0 issues
@developerkunal developerkunal requested a review from a team as a code owner November 24, 2025 05:12
@codecov-commenter
Copy link

codecov-commenter commented Nov 24, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (v3-dev@f5ad03e). Learn more about missing BASE report.

Additional details and impacted files
@@            Coverage Diff            @@
##             v3-dev     #361   +/-   ##
=========================================
  Coverage          ?   98.86%           
=========================================
  Files             ?       12           
  Lines             ?      707           
  Branches          ?        0           
=========================================
  Hits              ?      699           
  Misses            ?        4           
  Partials          ?        4           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  - Change version to string format ("2" not 2)
  - Move linter settings from top-level to linters.settings
  - Move exclusions to linters.exclusions with new structure
  - Remove unsupported output fields
  - Update exclusions format (presets, paths, rules)

  Verified with: golangci-lint config verify
@developerkunal developerkunal changed the title docs: add documentation and linting configuration for v3 chore(docs): PR 1.6 add documentation and linting configuration for v3 Nov 24, 2025
developerkunal and others added 10 commits November 24, 2025 11:27
  Remove duplicate context key management from HTTP middleware and use
  core's SetClaims/GetClaims/HasClaims functions consistently. This
  establishes the standard pattern for all adapters.

  Changes:
  - Remove contextKey and claimsContextKey from middleware.go
  - Update CheckJWT to use core.SetClaims() for storing claims
  - Update GetClaims/MustGetClaims/HasClaims to delegate to core
  - Update test assertion to match core's error message

  Benefits:
  - Single source of truth for context key management in core
  - All adapters (HTTP, gRPC, Gin, Echo) will use same context key
  - Claims stored by any adapter can be retrieved by any other adapter
  - Zero collision risk with unexported contextKey type in core
  - Maintains clean API - HTTP users don't need to import core

  This ensures cross-adapter compatibility while keeping the HTTP
  middleware API user-friendly with convenience wrappers.
- Change WithValidateToken to WithValidator to accept *validator.Validator
- Update ErrValidateTokenNil to ErrValidatorNil
- Refactor validatorAdapter to use TokenValidator interface
- Update all examples (http, http-jwks, gin, echo, iris) to use WithValidator
- Add setupRouter/setupApp functions to all examples for testability
- Create comprehensive integration tests for all examples
- Update test fixtures to use non-expiring test token (expires 2099)
- Add testify dependency to example projects for testing
- Fix iris example to use iris native httptest package

This change enables future extensibility for methods like ValidateDPoP
by allowing explicit passing of the validator instance.
…lidateToken

- Update doc.go with all examples using WithValidator
- Update README.md examples throughout
- Update MIGRATION_GUIDE.md with correct v3 API
- Update option.go comment example
- Align all documentation with the new API that accepts *validator.Validator instances

All documentation now correctly shows the v3 API where middleware
accepts validator instances via WithValidator, enabling future
extensibility for methods like ValidateDPoP.
Base automatically changed from v3-phase1-pr5-middleware-options to v3-dev December 8, 2025 06:31
@developerkunal developerkunal merged commit a280c5e into v3-dev Dec 8, 2025
6 checks passed
@developerkunal developerkunal deleted the v3-phase1-pr6-documentation-linting branch December 8, 2025 06:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants